package com.magima.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.ClipData;
import android.content.Context;
import android.os.Build;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommonUtil {
	public static JSONObject getJSONByResName(Context context, String name) {
		int id = context.getResources().getIdentifier(name, "raw", context.getPackageName());
		return getJSONByResId(context, id);
	}
	public static JSONObject getJSONByResId(Context context, int resourceId) {
		InputStream ins =  context.getResources().openRawResource(resourceId);

		String mResult = "";
		JSONObject json= null;

		try {
			int size = ins.available();
			byte[]buffer=new byte[size];

			while(ins.read(buffer)>0)
			{
				mResult += new String(buffer);
			}

			json =  new JSONObject(mResult);	    	 
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return json;
	}

	public static void hideSoftKeyboard(Context context){
		View focus_view = ((Activity)context).getCurrentFocus();
		if(focus_view != null){
			InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
			inputManager.hideSoftInputFromWindow(focus_view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	public static void hideSoftKeyboard(Context context, View view){
		InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
		inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}
	
	public static void showSoftKeyboard(Context context, View v){
		v.requestFocus();
		((InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(v, InputMethodManager.RESULT_SHOWN); 
	}
	
	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	public static void copyToClipBoard(Context context, String str){
		if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {	        		
			android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    		clipboard.setText(str);
    	} else {
    		android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); 
        	ClipData clip = ClipData.newPlainText(str, str);
        	clipboard.setPrimaryClip(clip);
    	}
	}
	
	/**
	 * 字符数，中文2个，英文一个
	 * @param str
	 * @return
	 */
	public static int getStringGBKBytesLength(String str){
		try{
			return str.getBytes("gbk").length;
		}catch (Exception e) {
			return 0;
		}
	}

	public static String join(String[] array, String splitStr){
		if(array == null)
			return "";
		
		StringBuilder str = new StringBuilder();
		
		for (int i = 0; i < array.length; i++) {
			str.append(array[i]);
			if (i != array.length - 1) {
				str.append(splitStr);
			}
		}
		
		return str.toString();
	}
	public static String join(int[] array, String splitStr){
		if(array == null)
			return "";

        StringBuilder str = new StringBuilder();
		
		for (int i = 0; i < array.length; i++) {
			str.append(array[i]);
			if (i != array.length - 1) {
				str.append(splitStr);
			}
		}
		
		return str.toString();
	}
	
	
	/**
	 * 关闭截屏 
	 */
	public static void disableScreenShot(Activity context){
		if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH )
			context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
	}
	
	
	/**
	 * 开启截屏
	 */
	public static void enableScreenShot(Activity context){
		if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH )
			context.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
	}
	
	public static MemoryInfo getMemoryInfo(Context context){
		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		MemoryInfo mi = new MemoryInfo();
		manager.getMemoryInfo(mi);
		return mi;
	}
	
	public static class DeviceInfo {
		public String osVersion;
		public String brand;
		public String board;
		public String cpu_abi;
		public String cpu_abi2;
		public String device;
		public String display;
		public String hardware;
		public String host;
		public String manufacturer;
		public String model;
		public String product;
		public String release;
		public int sdk;
	}
	public static DeviceInfo getDeviceInfo(){
		DeviceInfo deviceInfo = new DeviceInfo();
		deviceInfo.osVersion = System.getProperty("os.version");
		deviceInfo.brand = Build.BRAND;
		deviceInfo.board  = Build.BOARD;
		deviceInfo.cpu_abi = Build.CPU_ABI;
		deviceInfo.cpu_abi2 = Build.CPU_ABI2;
		deviceInfo.device = Build.DEVICE;
		deviceInfo.display = Build.DISPLAY;
		deviceInfo.hardware = Build.HARDWARE;
		deviceInfo.host = Build.HOST;
		deviceInfo.manufacturer = Build.MANUFACTURER;
		deviceInfo.model = Build.MODEL;
		deviceInfo.product = Build.PRODUCT;
		deviceInfo.release = Build.VERSION.RELEASE;
		deviceInfo.sdk = Build.VERSION.SDK_INT;
		return deviceInfo;
	}
	
	public static String getMyProcessName(Context context){
		int pid = android.os.Process.myPid();
		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		for ( RunningAppProcessInfo processInfo: manager.getRunningAppProcesses()){
			if ( processInfo.pid == pid ) {
				return processInfo.processName;
			}
		}
		return null;
	}
	
	public static boolean isForeground(Context context){
		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
		for(RunningAppProcessInfo process : processes){
			if(process.processName.equals(context.getPackageName())){
				if(process.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
					return true;
				}else{
					return false;
				}
			}
		}
		return false;
	}
	
	public static boolean startWithAlphabet(String str){
		if ( str == null || str.equals("") )
			return false;
		if ( str.getBytes()[0] >= "a".getBytes()[0] && 
				str.getBytes()[0] <= "z".getBytes()[0])
			return true;
		if ( str.getBytes()[0] >= "A".getBytes()[0] && 
				str.getBytes()[0] <= "Z".getBytes()[0])
			return true;
		return false;
	}

    public static int getWindowWidth(Context context){
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getWidth();
    }

    public static int getWindowHeight(Context context){
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getHeight();
    }
    
    /**
     * 获取带alpha的颜色值
     * @param color
     * @param percent
     * @return
     */
    public static int getAlphaColor(int color, float percent){
    	return ( (int)( 255 * percent )<<24 ) | (color & 0x00ffffff);
    }
    
   /**
    * 获取渐变颜色值
    * @param toColor
    * @param fromColor
    * @param percent
    * @return
    */
    public static int getGradientColor(int toColor, int fromColor, float percent){
    	int delaR = ((toColor & 0xff0000) >> 16) - ((fromColor & 0xff0000) >> 16);
    	int delaG = ((toColor & 0x00ff00) >> 8) - ((fromColor & 0x00ff00) >> 8);
    	int delaB = (toColor & 0x0000ff) - (fromColor & 0x0000ff);
    	int curColor = (((fromColor & 0xff0000) + ((int)(delaR * percent) << 16))
    			| ((fromColor & 0x00ff00) + ((int)(delaG * percent) << 8))
    			| ((fromColor & 0x0000ff) + (int)(delaB * percent))) 
    			| 0xff000000;
    	return curColor;
    }
    
    public static String getImageUrlWithHashCodeSurFix(String url){
    	return url.replaceFirst("\\.(jpg|jpeg|png|bmp|gif|JPG|JPEG|PNG|BMP|GIF)$", "." + url.hashCode());
    }

    public static String getVoiceUrlWithHashCodeSurFix(String url) {
        return url.replaceFirst("\\.(mp4)$", "." + url.hashCode());
    }

    /**
     * 解析获取url参数的键值对
     * @param url
     * @return
     */
    public static Map<String, String> getUrlParams(String url){
        Map<String, String> map = new HashMap<String, String>();

        String[] urlSplit = url.split("[?]");
        String paramsStr = "";
        if(urlSplit.length == 2){
            paramsStr = urlSplit[1];
        }

        if(!paramsStr.isEmpty()){
            String[] paramsSplit = paramsStr.split("[&]");

            for(String param : paramsSplit){
                String[] paramSplit = param.split("[=]");
                if(paramSplit.length == 2){
                    map.put(paramSplit[0], paramSplit[1]);
                }
            }
        }

        return map;
    }
}
